﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Windows.Navigation;
using System.Diagnostics;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Controls.Primitives;
using ProtoType.ProtoTypeService;
using ProtoType.DataStorage;
using Microsoft.Phone;
using System.IO.IsolatedStorage;

namespace ProtoType
{
    public partial class FormDataEntry : PhoneApplicationPage
    {
        AppSettings apps = new AppSettings();
        ProtoTypeServiceClient client;
        DataStructureStore dss = new DataStructureStore();
        PhotoChooserTask photoChooserTask;
        Image Img = new Image();
        BitmapImage bmp = new BitmapImage();
        private byte[] _imageBytes = null;
        int flag = 0;
        string ImgPath = "Images/AddImage.png";
        string selectedfid = "";
        string focusItemvalue = "";
        bool NewpageInstance = false;

        public FormDataEntry()
        {
            InitializeComponent();
            NewpageInstance = true;
            client = new ProtoTypeServiceClient();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.TryGetValue("fid", out selectedfid) && flag == 0)
            {
                if (NewpageInstance)
                {
                    DisignDataEntryForm(selectedfid);
                }
                NewpageInstance = false;
            }
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            var list = new List<KeyValuePair<string, string>>();
            Dictionary<string, string> dtlist = new Dictionary<string, string>();
            DataTemplates dt = new DataTemplates();
            IEnumerable<DependencyObject> tboxes = dt.GetChildsRecursive(lstform);
            foreach (DependencyObject obj in tboxes.OfType<DependencyObject>())
            {
                Type type = obj.GetType();
                if (type.Name == "TextBox")
                {
                    TextBox tb = obj as TextBox;
                    if (tb.Name != "DisabledOrReadonlyContent")
                        dtlist.Add(tb.Name.Replace(" ", ""), tb.Text);
                }
                if (type.Name == "Image")
                {
                    Image tb = obj as Image;
                    DateTime dot = System.DateTime.Now;
                    string Imgname = "Img" + dot.Millisecond.ToString() + ".jpg";
                    if (tb.Name != "")
                    {
                        dtlist.Add(tb.Name.Replace(" ", ""), Imgname);
                        SaveToLocalStorage(Imgname, "Images");
                    }
                }
                if (type.Name == "DatePicker")
                {
                    DatePicker tb = obj as DatePicker;
                    dtlist.Add(tb.Name.Replace(" ", ""), tb.ValueString);
                }
                if (type.Name == "TimePicker")
                {
                    TimePicker tb = obj as TimePicker;
                    dtlist.Add(tb.Name.Replace(" ", ""), tb.Value.ToString());
                }
            }
            if (apps.IsolatedStorageSavingSetting)
            {
                dss.AddFormItemDetails(dtlist, selectedfid);
                NavigationService.Navigate(new Uri("/FormData.xaml?fid=" + selectedfid, UriKind.Relative));
            }
            if (apps.WebServiceSavingSetting)
            {
                client.AddFormItemDetailsAsync(dtlist, selectedfid);
                client.AddFormItemDetailsCompleted += new EventHandler<AddFormItemDetailsCompletedEventArgs>(client_AddFormItemDetailsCompleted);
            }
        }

        private void SaveToLocalStorage(string fileName, string imageFolder)
        {
            if (_imageBytes == null)
            {
                return;
            }
            var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (!isoFile.DirectoryExists(imageFolder))
            {
                isoFile.CreateDirectory(imageFolder);
            }
            string filePath = System.IO.Path.Combine(imageFolder, fileName);
            using (var stream = isoFile.CreateFile(filePath))
            {
                stream.Write(_imageBytes, 0, _imageBytes.Length);
            }
        }

        void client_AddFormItemDetailsCompleted(object sender, AddFormItemDetailsCompletedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/FormData.xaml?fid=" + selectedfid, UriKind.Relative));
        }

        void DisignDataEntryForm(string formid)
        {
            if (apps.IsolatedStorageSavingSetting)
            {
                LoadformControlList(dss.LoadformControlList(selectedfid));
            }
            if (apps.WebServiceSavingSetting)
            {
                client.LoadformControlListAsync(formid);
                client.LoadformControlListCompleted += new EventHandler<LoadformControlListCompletedEventArgs>(client_LoadformControlListCompleted);
            }
        }
        void client_LoadformControlListCompleted(object sender, LoadformControlListCompletedEventArgs e)
        {
            LoadformControlList(e.Result);
        }

        void LoadformControlList(ObservableCollection<XElement> controls)
        {
            StackPanel sp = new StackPanel();
            sp.Name = "sp1";
            foreach (var c in controls.Elements("control"))
            {
                CreateControl(c.Attribute("id").Value, c.Element("cname").Value, c.Element("ctype").Value, false, sp);
            }
            lstform.Items.Add(sp);
        }
        void CreateControl(string cid, string cname, string ctype, bool display, StackPanel sp)
        {

            DataTemplates dt = new DataTemplates();
            TextBlock tblock = dt.CreateATextBlock(cname);
            switch (ctype)
            {
                case "Address":
                    var AddressScope = new InputScopeName { NameValue = InputScopeNameValue.AddressStateOrProvince };
                    TextBox Addresstbox = dt.CreateATextBox(cname, AddressScope);
                    Addresstbox.Tag = cid.ToString();
                    Addresstbox.AcceptsReturn = true;
                    Addresstbox.Height = 150;

                    sp.Children.Add(tblock);
                    sp.Children.Add(Addresstbox);
                    break;

                case "Audio":
                    var AudioScope = new InputScopeName { NameValue = InputScopeNameValue.Text };
                    TextBox Audiotbox = dt.CreateATextBox(cname, AudioScope);
                    Audiotbox.Tag = cid.ToString();

                    StackPanel spChildAudio = new StackPanel();
                    spChildAudio.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    Image AudioImg = new Image();
                    BitmapImage Audiobmp = new BitmapImage();
                    Audiobmp.UriSource = new Uri("Images/Audio.png", UriKind.Relative);
                    AudioImg.Stretch = Stretch.Fill;
                    AudioImg.Source = Audiobmp;
                    AudioImg.Height = 30;
                    AudioImg.Width = 32;

                    spChildAudio.Children.Add(Audiotbox);
                    spChildAudio.Children.Add(AudioImg);

                    sp.Children.Add(tblock);
                    sp.Children.Add(spChildAudio);
                    break;

                case "Currency":
                    var CurrencyScope = new InputScopeName { NameValue = InputScopeNameValue.CurrencyAmount };
                    TextBox Currencytbox = dt.CreateATextBox(cname, CurrencyScope);
                    Currencytbox.Tag = cid.ToString();
                    sp.Children.Add(tblock);
                    sp.Children.Add(Currencytbox);
                    break;

                case "Date":
                    DatePicker dp = new DatePicker();
                    dp.Name = "dp" + cname;
                    dp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    dp.GotFocus += new RoutedEventHandler(dp_GotFocus);
                    dp.Width = 430;
                    dp.Tag = cid.ToString();

                    sp.Children.Add(tblock);
                    sp.Children.Add(dp);
                    break;

                case "Email":
                    var EmailScope = new InputScopeName { NameValue = InputScopeNameValue.EmailNameOrAddress };
                    TextBox Emailtbox = dt.CreateATextBox(cname, EmailScope);
                    Emailtbox.Tag = cid.ToString();
                    sp.Children.Add(tblock);
                    sp.Children.Add(Emailtbox);
                    break;

                case "Image":
                    var ImageScope = new InputScopeName { NameValue = InputScopeNameValue.Text };
                    TextBox Imagetbox = dt.CreateATextBox(cname, ImageScope);
                    Imagetbox.Tag = cid.ToString();

                    StackPanel stkpnlchildImage = new StackPanel();
                    stkpnlchildImage.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    Img.Name = cname;
                    Img.MouseEnter += new MouseEventHandler(Img_MouseEnter);
                    Img.Tag = cid.ToString();
                    bmp.UriSource = new Uri(ImgPath, UriKind.Relative);
                    Img.Stretch = Stretch.Fill;
                    Img.Source = bmp;
                    Img.Height = 45;
                    Img.Width = 80;

                    //stkpnlchildImage.Children.Add(Imagetbox);
                    stkpnlchildImage.Children.Add(Img);

                    sp.Children.Add(tblock);
                    sp.Children.Add(stkpnlchildImage);
                    break;

                case "Number":
                    var NumberScope = new InputScopeName { NameValue = InputScopeNameValue.Number };
                    TextBox Numbertbox = dt.CreateATextBox(cname, NumberScope);
                    Numbertbox.Tag = cid.ToString();
                    sp.Children.Add(tblock);
                    sp.Children.Add(Numbertbox);
                    break;

                case "Phone":
                    var PhoneScope = new InputScopeName { NameValue = InputScopeNameValue.TelephoneNumber };
                    TextBox Phonetbox = new TextBox();
                    Phonetbox = dt.CreateATextBox(cname, PhoneScope);
                    Phonetbox.Tag = cid.ToString();

                    StackPanel phonechildstcpanel = new StackPanel();
                    phonechildstcpanel.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    Image PhoneImg = new Image();
                    BitmapImage Phonebmp = new BitmapImage();
                    Phonebmp.UriSource = new Uri("Images/Phone.png", UriKind.Relative);
                    PhoneImg.Stretch = Stretch.Fill;
                    PhoneImg.MouseEnter += new MouseEventHandler(PhoneImg_MouseEnter);
                    PhoneImg.Tag = cid.ToString();
                    PhoneImg.Source = Phonebmp;
                    PhoneImg.Height = 36;
                    PhoneImg.Width = 21;

                    phonechildstcpanel.Children.Add(Phonetbox);
                    phonechildstcpanel.Children.Add(PhoneImg);

                    sp.Children.Add(tblock);
                    sp.Children.Add(phonechildstcpanel);
                    break;

                case "Text":
                    var TextScope = new InputScopeName { NameValue = InputScopeNameValue.Maps };
                    TextBox Texttbox = dt.CreateATextBox(cname, TextScope);
                    Texttbox.Tag = cid.ToString();
                    sp.Children.Add(tblock);
                    sp.Children.Add(Texttbox);
                    break;

                case "Time":
                    TimePicker tp = new TimePicker();
                    tp.Name = "tp" + cname;
                    tp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    tp.GotFocus += new RoutedEventHandler(tp_GotFocus);
                    tp.Width = 430;
                    tp.Tag = cid.ToString();

                    sp.Children.Add(tblock);
                    sp.Children.Add(tp);
                    break;

                case "Url":
                    var UrlScope = new InputScopeName { NameValue = InputScopeNameValue.Url };
                    TextBox Urltbox = dt.CreateATextBox(cname, UrlScope);
                    Urltbox.Tag = cid.ToString();
                    sp.Children.Add(tblock);
                    sp.Children.Add(Urltbox);
                    break;

                case "Video":
                    var VideoScope = new InputScopeName { NameValue = InputScopeNameValue.Text };
                    TextBox Videotbox = dt.CreateATextBox(cname, VideoScope);
                    Videotbox.Tag = cid.ToString();

                    StackPanel spChildVideo = new StackPanel();
                    spChildVideo.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    Image VideoImg = new Image();
                    BitmapImage Videobmp = new BitmapImage();
                    Videobmp.UriSource = new Uri("Images/Video.png", UriKind.Relative);
                    VideoImg.Stretch = Stretch.Fill;
                    VideoImg.Source = Videobmp;
                    VideoImg.Height = 29;
                    VideoImg.Width = 30;

                    spChildVideo.Children.Add(Videotbox);
                    spChildVideo.Children.Add(VideoImg);

                    sp.Children.Add(tblock);
                    sp.Children.Add(spChildVideo);
                    break;
            }
        }

        void Img_MouseEnter(object sender, MouseEventArgs e)
        {
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Show();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                _imageBytes = new byte[e.ChosenPhoto.Length];
                e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);

                // Seek back so we can create an image.
                e.ChosenPhoto.Seek(0, SeekOrigin.Begin);

                // Create an image from the stream.
                var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                Img.Source = imageSource;


            }
        }

        void tp1_GotFocus(object sender, RoutedEventArgs e)
        {
            flag = 1;
        }

        void dp1_GotFocus(object sender, RoutedEventArgs e)
        {
            flag = 1;
        }

        void tp_GotFocus(object sender, RoutedEventArgs e)
        {
            flag = 1;
        }
        void PhoneImg_MouseEnter(object sender, MouseEventArgs e)
        {
            Image hlkb = e.OriginalSource as Image;
            focusItemvalue = hlkb.Tag.ToString();
            PhoneNumberChooserTask phnchooetask = new PhoneNumberChooserTask();
            phnchooetask.Show();
            phnchooetask.Completed += new EventHandler<PhoneNumberResult>(phnchooetask_Completed);
        }

        void dp_GotFocus(object sender, RoutedEventArgs e)
        {
            flag = 1;
        }

        void phnchooetask_Completed(object sender, PhoneNumberResult e)
        {
            DataTemplates dt = new DataTemplates();
            IEnumerable<DependencyObject> tboxes = dt.GetChildsRecursive(lstform);
            foreach (DependencyObject obj in tboxes.OfType<TextBox>())
            {
                Type type = obj.GetType();
                if (type.Name == "TextBox")
                {
                    TextBox tb = obj as TextBox;

                    if (tb.Name != "DisabledOrReadonlyContent" && tb.Tag.ToString() == focusItemvalue)
                    {
                        tb.Text = e.PhoneNumber;
                    }
                }
            }
        }
    }
}